package com.example.declarative;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @description: 声明式事务启动类
 * @author: lzp
 * @createTime: 2021-11-21 11:45
 **/
@SpringBootApplication
@Slf4j
@EnableTransactionManagement(mode = AdviceMode.PROXY) // 默认PRXOY，可以扩展使用ASPECTJ
public class Application  implements CommandLineRunner {

    @Autowired
    private FooService fooService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        fooService.insertRecord();
        log.info("insertRecord: {}",
                jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO WHERE BAR='insertRecord'", Long.class));

        try {
            fooService.insertThenRollback();
        } catch (RollbackException e) {
            log.info("insertThenRollback: {}",
                    jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO WHERE BAR='insertThenRollback'", Long.class));
        }

        try {
            fooService.invokeInsertThenRollback();
        } catch (RollbackException e) {
            log.info("invokeInsertThenRollback: {}",
                    jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO WHERE BAR='insertThenRollback'", Long.class));
        }

    }
}
